#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新闻日报启动脚本
一键启动新闻日报定时发送服务
"""

import os
import sys
from datetime import datetime
from scheduler import NewsDailyScheduler, create_scheduler_from_config
from email_config import validate_config, get_config_info


def print_banner():
    """打印启动横幅"""
    print("=" * 60)
    print("📰 MorningByte 新闻日报系统")
    print("=" * 60)
    print(f"启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)


def check_dependencies():
    """检查依赖包是否安装"""
    required_packages = [
        ('openai', 'openai'), 
        ('requests', 'requests'), 
        ('feedparser', 'feedparser'), 
        ('beautifulsoup4', 'bs4'), 
        ('lxml', 'lxml'), 
        ('schedule', 'schedule')
    ]
    
    missing_packages = []
    
    for package_name, import_name in required_packages:
        try:
            __import__(import_name)
        except ImportError:
            missing_packages.append(package_name)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"  - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        return False
    
    print("✅ 所有依赖包已安装")
    return True


def check_config():
    """检查配置文件"""
    print("\n🔧 检查配置文件...")
    
    errors = validate_config()
    if errors:
        print("❌ 配置验证失败:")
        for error in errors:
            print(f"  - {error}")
        print("\n请修改 email_config.py 文件中的配置")
        return False
    
    print("✅ 配置验证通过")
    
    # 显示配置信息
    info = get_config_info()
    print("\n📋 当前配置:")
    print(f"  发送邮箱: {info['sender_email']}")
    print(f"  接收邮箱: {info['recipient_email']}")
    print(f"  RSS源: {info['rss_url']}")
    print(f"  发送时间: 每天 {info['send_time']}")
    print(f"  最大新闻数: {info['max_news_items']}")
    
    return True


def test_email_connection():
    """测试邮件连接"""
    print("\n📧 测试邮件连接...")
    
    try:
        from email_config import SENDER_EMAIL, SENDER_PASSWORD, RECIPIENT_EMAIL
        from email_sender import create_qq_email_sender
        
        # 创建邮件发送器
        sender = create_qq_email_sender(SENDER_EMAIL, SENDER_PASSWORD)
        
        # 创建测试邮件
        test_news = {
            'title': '连接测试',
            'description': '这是一封测试邮件',
            'last_updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'total_items': 1,
            'items': [{
                'title': '邮件连接测试',
                'link': 'https://example.com',
                'published': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'description': '如果您收到这封邮件，说明邮件配置正确。'
            }]
        }
        
        # 发送测试邮件
        success = sender.send_news_daily(RECIPIENT_EMAIL, test_news, "这是一封测试邮件，用于验证邮件配置是否正确。")
        
        if success:
            print("✅ 邮件连接测试成功")
            return True
        else:
            print("❌ 邮件发送失败")
            return False
            
    except Exception as e:
        print(f"❌ 邮件连接测试失败: {e}")
        return False


def start_scheduler():
    """启动调度器"""
    print("\n🚀 启动新闻日报调度器...")
    
    try:
        # 从配置文件创建调度器
        scheduler = create_scheduler_from_config()
        
        if not scheduler:
            print("❌ 无法创建调度器")
            return False
        
        # 显示调度器状态
        scheduler.show_status()
        
        print("\n📝 调度器已启动，按 Ctrl+C 停止")
        print("💡 提示: 日志文件保存在 logs/ 目录中")
        
        # 运行调度器
        scheduler.run()
        
        return True
        
    except KeyboardInterrupt:
        print("\n\n👋 调度器已停止")
        return True
    except Exception as e:
        print(f"\n❌ 调度器运行失败: {e}")
        return False


def main():
    """主函数"""
    print_banner()
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 检查配置
    if not check_config():
        sys.exit(1)
    
    # 询问是否测试邮件连接
    test_email = input("\n是否测试邮件连接? (y/n): ").strip().lower()
    if test_email in ['y', 'yes', '是']:
        if not test_email_connection():
            print("\n⚠️  邮件连接测试失败，但您仍可以继续启动调度器")
            continue_anyway = input("是否继续启动? (y/n): ").strip().lower()
            if continue_anyway not in ['y', 'yes', '是']:
                sys.exit(1)
    
    # 启动调度器
    start_scheduler()


if __name__ == "__main__":
    main()
